/**
 * Created by liuyu on 29/10/2016.
 */
'use strict';

const fs = require('fs');

function addMapping(router, mapping) {
    for (let url in mapping) {
        if (url.startsWith('GET')) {
            let path = url.substring(4);
            router.get(path, mapping[url]);
        } else if (url.startsWith('POST')) {
            let path = url.substring(5);
            router.post(path, mapping[url]);
        } else {
            console.log(`${url}`);
        }
    }
}

function addControllers(router) {
    var files = fs.readdirSync(__dirname + '/controller');
    var js_files = files.filter((f)=> {
        return f.endsWith('.js');
    }, files);

    for (let f of js_files) {
        let mapping = require(__dirname + '/controller/' + f);
        addMapping(router, mapping);
    }
}

module.exports = (dir)=> {
    let
        controllers_dir = dir || 'controller',
        router = require('koa-router')();
    addControllers(router, controllers_dir);
    return router.routes();
};
